<?php
/**
 * [LupMisNotAllowedSync]
 * 本代码为系统自动生成代码，请根据自己业务进行修改;
 * 生成时间 2022-02-18 18:16:27;
 * 版权所有 2020-2022 lizhongwen，并保留所有权利;
 * 说明: 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用；不允许对程序代码以任何形式任何目的的再发布;
 * 作者: 中文Lee;
 * 作者主页: http://www.lizhongwen.com;
 * 邮箱: 360811363@qq.com;
 * QQ: 360811363;
 */

namespace modules\sys\service\impl;

use application\core\Result;
use application\core\SnowFlake;
use Exception;
use modules\sys\component\SetCacheComponent;
use modules\sys\mapper\FieldMapper;
use modules\sys\mapper\MysqlMapper;
use modules\sys\mapper\TableMapper;
use modules\sys\service\TableService;

class TableServiceImpl implements TableService
{


    public function lists(array $data = [], array $pagePars = []): array
    {
        return Result::success(false, TableMapper::lists($data, $pagePars));
    }


    public function add(array $data): array
    {
        //判断表前缀

        if (empty(TABLE_PREFIX)) {
            return Result::fail(false, [], "请先设置表前缀.");
        }
        $prefixArr = explode(",", TABLE_PREFIX);
        $arr = explode("_", $data['table_name']);
        if (!in_array($arr[0] . "_", $prefixArr)) {
            return Result::fail(false, [], "表前缀不正确，只能添加表前缀为【" . TABLE_PREFIX . "】的表.");
        }
        $mysqlMapper = new MysqlMapper();
        $fieldMapper = new FieldMapper();
        try {
            $data['id'] = SnowFlake::instance()->nextId();
            $add = TableMapper::add($data);
            if ($add == 0) {
                return Result::fail(false, [], "数据表添加失败.");
            }
            //添加数据表字段
            $fieldData = [
                'id' => SnowFlake::instance()->nextId(),
                'table_name' => $data['table_name'],
                'field_name' => 'id',
                'field_remarks' => 'ID',
                'field_type' => 'bigint',
                'field_len' => 19,
                'field_default_value' => '0',
                'data_src_type' => 'none',
                'data_check_type' => 'none',
                'input_type' => 'input',
                'cols_width' => 0,
                'must' => 1,
                'list_edit' => -1,
                'list_show' => -1,
                'search_condition' => 'none',
                'sort' => 1,
                'dict_code' => '',
                'custom_src' => '',
                'is_allow_replace' => -1,
                'remarks' => '系统生成字段'
            ];
            $fieldMapper->add($fieldData);
            //添加数据创建时间
            $fieldData = [
                'id' => SnowFlake::instance()->nextId(),
                'table_name' => $data['table_name'],
                'field_name' => 'create_time',
                'field_remarks' => '创建时间',
                'field_type' => 'datetime',
                'field_len' => 0,
                'field_default_value' => '1970-01-01 08:00:00',
                'data_src_type' => 'none',
                'data_check_type' => 'ymdhis',
                'input_type' => 'input',
                'cols_width' => 140,
                'must' => 1,
                'list_edit' => -1,
                'list_show' => -1,
                'search_condition' => 'none',
                'sort' => 9999,
                'dict_code' => '',
                'custom_src' => '',
                'is_allow_replace' => -1,
                'remarks' => '系统生成字段'
            ];
            $fieldMapper->add($fieldData);

            SetCacheComponent::table();
            SetCacheComponent::field();
        } catch (Exception $e) {
            return Result::fail(false, [], "数据表字段添加失败。" . $e->getMessage());
        }
        try {
            $tableData = [
                'table_name' => $data['table_name'],
                'table_remarks' => $data['table_remarks']
            ];
            $mysqlMapper->createTable($tableData);
        } catch (Exception $e) {
            return Result::success(true, [], "<b style='color: red'>数据表创建失败</b>,请手动创建数据表");
        }
        return Result::success(true, [], "添加成功");
    }

    public function edit(array $data): array
    {
        $queryRs = TableMapper::query(['id' => $data['id']]);
        $oldTableName = $queryRs['table_name'];
        $newTableName = $data['table_name'];
        $tableRemarks = $data['table_remarks'];
        $fieldMapper = new FieldMapper();
        $fieldMapper->editTableName(['new_table_name' => $newTableName, 'old_table_name' => $oldTableName]);
        try {
            $tableData = [
                'new_table_name' => $newTableName,
                'old_table_name' => $oldTableName,
                'table_remarks' => $tableRemarks
            ];
            $mysqlMapper = new MysqlMapper();
            $mysqlMapper->editTable($tableData);
        } catch (Exception $e) {
            return Result::success(true, [], "<b style='color: red'>数据表修改失败</b>,请手动修改数据表");
        }

        $edit = TableMapper::edit($data);
        if ($edit == 0) {
            return Result::fail(false, [], "您未修改任何数据");
        }
        SetCacheComponent::table();
        return Result::success(true, [], "修改成功");
    }

    public function query(array $data): array
    {
        return Result::success(false, TableMapper::query($data));
    }

    public function del(array $data): array
    {
        //判断该数据表下是否有字段
        $queryRs = TableMapper::query(['id' => $data['ids']]);
        $tableName = $queryRs['table_name'];
        $fieldMapper = new FieldMapper();
        $queryByTableName = $fieldMapper->queryByTableName(['table_name' => $tableName]);
        if (!empty($queryByTableName)) {
            return Result::fail(false, [], "请先删除该数据表下的字段");
        }
        $del = TableMapper::del(['id' => $data['ids']]);
        if ($del == 0) {
            return Result::fail(false, [], "删除失败，数据不存在");
        }
        SetCacheComponent::table();
        return Result::success(true, [], "删除成功");
    }
}

